package com.founder.android;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.Animation.AnimationListener;
import android.widget.ImageView;

public class MenuPlayActivity extends Activity implements ScrollTextViewCallBack {
	
	private List<AnimationPair> animations = new ArrayList<AnimationPair>();
	
	private Random random = new Random();
	
	private static final int MAX_WIDTH = 240;
	
	private static final int MAX_HEIGHT = 320;
	
	private static final int PERIOD_TIME = 5 * 1000;
	
	private ImageView outImageView;
	
	private ImageView inImageView;
	
	private List<File> files;
	
	private Timer playTimer;
	
	private int picIndex;
	
	private Bitmap inBmp;
	
	private Bitmap outBmp;
	
	private AutoScrollTextView textView;
	
	private List<String> textlist = new ArrayList<String>();
	
	private int txtIndex;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.screen_picture);
        
        outImageView = (ImageView) findViewById(R.id.outImageView);
        inImageView = (ImageView) findViewById(R.id.inImageView);
        initAnimation();
		
        initTexts();
        textView = (AutoScrollTextView) findViewById(R.id.textView);
        textView.setCallback(this);
        txtIndex = 0;
        if (textlist.size() > 0) {
        	textView.configView(textlist.get(txtIndex));
	        textView.startScroll();
        }
		
        String dir = getIntent().getStringExtra("dir");
		String path = PlayerUtil.getPath(dir);
		files = PlayerUtil.filterDirFile(path, PlayerUtil.TYPE_IMAGE);
		
		picIndex = 0;
		if (files.size() > 0) {
			loadPicture(files.get(picIndex));
			playTimer = new Timer();
	    	playTimer.schedule(new TimerTask(){
	    		@Override
	    		public void run() {
	    			handler.sendEmptyMessage(0);
	    		}
	    	}, PERIOD_TIME, PERIOD_TIME);
		} else {
			finish();
		}
	}
	
	@Override
	public void finished() {
		txtIndex++;
		if (txtIndex == textlist.size()) {
			txtIndex = 0;
		}
		textView.configView(textlist.get(txtIndex));
        textView.startScroll();
	}
	
	private void initTexts() {
		String path = PlayerUtil.getPath("txt");
		List<File> txtFiles = PlayerUtil.filterDirFile(path, PlayerUtil.TYPE_TXT);
		for (File f : txtFiles) {
			try {
				FileInputStream in = new FileInputStream(f);
				try {
					BufferedReader reader = new BufferedReader(new InputStreamReader(in, "gb2312"));
					try {
						String line = null;
						while ((line = reader.readLine()) != null) {
							textlist.add(line);
						}
					} finally {
						reader.close();
					}
				} finally {
					in.close();
				}
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
				textlist.add("Error:" + e.getMessage());
			} catch (FileNotFoundException e) {
				e.printStackTrace();
				textlist.add("Error:" + e.getMessage());
			} catch (IOException e) {
				e.printStackTrace();
				textlist.add("Error:" + e.getMessage());
			}
		}
	}

	private void initAnimation() {
		animations.add(new AnimationPair(
				AnimationUtils.loadAnimation(this, R.anim.alpha_out), 
				AnimationUtils.loadAnimation(this, R.anim.alpha_in)));
		animations.add(new AnimationPair(
				AnimationUtils.loadAnimation(this, R.anim.left_out), 
				AnimationUtils.loadAnimation(this, R.anim.right_in)));
		animations.add(new AnimationPair(
				AnimationUtils.loadAnimation(this, R.anim.rotate_out), 
				AnimationUtils.loadAnimation(this, R.anim.rotate_in)));
		animations.add(new AnimationPair(
				AnimationUtils.loadAnimation(this, R.anim.scale_out_screen), 
				AnimationUtils.loadAnimation(this, R.anim.scale_in_screen)));
		animations.add(new AnimationPair(
				AnimationUtils.loadAnimation(this, R.anim.scale_rotate_out), 
				AnimationUtils.loadAnimation(this, R.anim.scale_rotate_in)));
		animations.add(new AnimationPair(
				AnimationUtils.loadAnimation(this, R.anim.bottom_out), 
				AnimationUtils.loadAnimation(this, R.anim.top_in)));
	}
	
	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			picIndex++;
			if (picIndex >= files.size()) {
				playTimer.cancel();
				finish();
			} else {
				loadPicture(files.get(picIndex));
			}
		}
	};

	private void loadPicture(File file) {
		
		if (inBmp != null) {
			outBmp = inBmp;
			outImageView.setImageBitmap(outBmp);
		}
		
		BitmapFactory.Options options = new BitmapFactory.Options();
		options.inSampleSize = 1;
		options.inJustDecodeBounds = true;
		BitmapFactory.decodeFile(file.getAbsolutePath(), options);
    	
		if (options.outHeight > MAX_HEIGHT || options.outWidth > MAX_WIDTH) {
			options.inSampleSize = PlayerUtil.computeSampleSize(options, -1, MAX_WIDTH * MAX_HEIGHT);
		}
		options.inJustDecodeBounds = false;
		inBmp = BitmapFactory.decodeFile(file.getAbsolutePath(), options);
		inImageView.setImageBitmap(inBmp);
    	
    	int animIndex = random.nextInt(animations.size());
    	//Log.e("MenuPlayActivity", "animIndex=" + animIndex);
    	AnimationPair pair = animations.get(animIndex);
    	outImageView.startAnimation(pair.slideLeftOut);
    	inImageView.startAnimation(pair.slideRightIn);
	}
	
	
	
	@Override
	protected void onStop() {
		//Log.e("MenuPlayActivity", "onStop is run");
		textView.stopScroll();
		super.onStop();
	}



	private class AnimationPair implements AnimationListener {
		
		Animation slideLeftOut;
		
		Animation slideRightIn;
		
		public AnimationPair(Animation slideLeftOut, Animation slideRightIn) {
			this.slideLeftOut = slideLeftOut;
			this.slideRightIn = slideRightIn;
			slideRightIn.setAnimationListener(this);
		}

		@Override
		public void onAnimationEnd(Animation animation) {
			//Log.e("MenuPlayActivity", "onAnimationEnd is run");
			outImageView.setImageBitmap(null);
			if (outBmp != null) {
				outBmp.recycle();
				outBmp = null;
			}
		}

		@Override
		public void onAnimationRepeat(Animation animation) {
			//Log.e("MenuPlayActivity", "onAnimationRepeat is run");
		}

		@Override
		public void onAnimationStart(Animation animation) {
			//Log.e("MenuPlayActivity", "onAnimationStart is run");
		}
	}
}
